package org.aoao.utils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class MyDes {

    //GBK 编码
    private String ENCODE="utf-8";

    //Des key 和加密解密对象 cipher
    private String key;
    private SecretKey secretKey;
    private Cipher cipher;
    public MyDes(){
        this("test1234");
    }

    public MyDes(String key) {
        this.key = key;
        try {
            // 获取 keySpec 实例
            DESKeySpec keySpec=new DESKeySpec(key.getBytes(ENCODE));
            // 获取工厂实例
            SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("des");
            // 获取 私钥
            secretKey=keyFactory.generateSecret(keySpec);
            // 实例化 加密工具
            cipher=Cipher.getInstance("des");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setKey(String key) {
        this.key = key;
    }

    // 将 plainText 加密 并返回 密文字符串
    public String encrypt(String plainText){
        String cipherText=null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE,secretKey,new SecureRandom());
            byte[] cipherData=cipher.doFinal(plainText.getBytes(ENCODE));
            return base64String(cipherData);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    // 将 cipherText 解密 并返回 明文字符串
    public String decrypt(String cipherText){
        String plainText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE,secretKey,new SecureRandom());

            byte[] plainData=cipher.doFinal(base64Bytes(cipherText));

            plainText=new String(plainData,ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return plainText;
    }

    //用base64 将字符串text 解码
    private byte[] base64Bytes(String text){
        return Base64.getDecoder().decode(text);
    }
    //用base64 将字节码data 编码
    private String base64String(byte[] data){
        return Base64.getEncoder().encodeToString(data);
    }

    public static void main(String[] args) {
        MyDes myDes=new MyDes("12345678");
        System.out.println(myDes.encrypt("201820109刘张澳"));
        System.out.println(myDes.decrypt("XpIjZLMehfhA1F2vrqcR4ezoyK6zFOmy"));
    }
}
